<template>
  <div class="countDown">
    <span class="time">
      <span v-if="!isH5">剩余可用时间: </span>
      <span>{{ remainingTime }}</span>
    </span>
    <el-tooltip placement="top">
      <span class="tips el-icon-warning"></span>

       <div slot="content">
         <Tips />
       </div>
    </el-tooltip>
  </div>
</template>


<script>
import { storageGet } from '@/utill/storage.js';
import Tips from './tips/index.vue';

export default {
  components: {
    Tips
  },
  props: {
    isH5: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    this.countDown();
  },
  data() {
    return {
      remainingTime: '计算中,请稍等...'
    };
  },
  methods: {
    countDown () {
      const deadLine = storageGet('deadline');
      let time= new Date(deadLine).getTime();
      let curTime = new Date().getTime();

      let countdown = setInterval(() => {
        curTime += 1000
        if (curTime <= time) {
          let distance = time - curTime;

          this.remainingTime = this.formatDate(distance);
        } else {
          this.remainingTime = '00 : 00 : 00';
          clearInterval(countdown)
        }
      }, 1000);
    },
    fillZero (num) {
      return num < 10 ? `0${num}` : num 
    },
    formatDate (timestamp) {
      // 总秒数
      let second = Math.floor(timestamp / 1000);
      // 天数
      let day = Math.floor(second / 3600 / 24);
      // 小时
      let hr = Math.floor(second / 3600 % 24);
      // 分钟
      let min = Math.floor(second / 60 % 60);
      // 秒
      let sec = Math.floor(second % 60);
      
      return `${day} 天 ${this.fillZero(hr)}:${this.fillZero(min)}:${this.fillZero(sec)}`;
    }
  }
}
</script>